import {delDir, updateResFile} from "../util/file";
import { getCatalogues } from "./catalogue";
import { findTargetNode, deleteTargetNode, deleteAllFiles } from "../util/tree";
const dataLocation = `${__dirname}/../data/catalogues.json`

// 删除节点
export const deleteNode = async ({mainId}) => {
  let tree = await getCatalogues()
  const target = findTargetNode({mainId, tree})
  if (!target) {
    return {
      data: false,
      message: '要删除的目标节点不存在！'
    }
  }
  const isDeleteFile = target.type === 2
  // 如果删除的是文件，那么也要删除该文件对应的兄弟元素，id为bro
  if (isDeleteFile) {
    delDir({path: target.fileDir, isDeleteSelf: true})
    deleteTargetNode({mainId, isDeleteSelf: true, tree})
    deleteTargetNode({mainId: target.bro, isDeleteSelf: true, tree})
  } else {
    // 删除目标文件夹下的所有文件，如果是删除文件夹，则连目标文件夹一并删除
    deleteAllFiles([target])
    deleteTargetNode({mainId, isDeleteSelf: true, tree})
  }
  return await updateResFile(dataLocation, tree)
}

export default {
  deleteNode
}
